package com.hualan.zhsq.utils;

import com.hualan.zhsq.constant.CommonConstant;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController

public class FileController {

    private String rootPath = CommonConstant.ROOT_PATH;

    @RequestMapping("/upload")
    public Result fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件!");
        }
        // 获取上传的文件的文件名
        String fileName = file.getOriginalFilename();
        //判空
        if (fileName == null) {
            return Result.error("文件名为空!");
        }
        // 处理文件重名问题: 截取文件扩展名，用UUID替代文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + suffix;
        // 当前日期文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateDirPath = sdf.format(new Date());

        String url = "";
        // 上传文件到OSS
        try {
            url = OSSUtils.upload(dateDirPath + "/" + fileName,
                    file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(url);
    }

    /**
     * 文件下载
     *
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping("/download")
    public void fileDownload(String filePath, HttpServletResponse response, HttpSession session) throws IOException {
        // 创建输入流，读取文件
        FileInputStream fis = new FileInputStream(rootPath + "/" + filePath);
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachement;filename=" + filePath.substring(filePath.lastIndexOf("/") + 1));
        // 获取输出流
        ServletOutputStream out = response.getOutputStream();
        // 拷贝
        IOUtils.copy(fis, out);
    }

}

